<template>
  <div id="app" style="width: 85vw;">
    <div class="content-header">
      <h1>功能管理<small>汽车管理</small></h1>
      <el-breadcrumb separator-class="el-icon-arrow-right" class="breadcrumb">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>功能管理</el-breadcrumb-item>
        <el-breadcrumb-item>汽车管理</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="app-container">
      <div class="box">
        <div class="filter-container">
          <el-input placeholder="汽车品牌/型号" v-model="pagination.queryString" style="width: 200px;" class="filter-item"
                    @keyup.enter.native="handleFilter"/>
          <el-button @click="findPage" class="dalfBut">查询</el-button>
          <el-button type="primary" class="butT" @click="handleCreate">新增汽车信息</el-button>
        </div>

        <el-table size="small" :data="dataList" stripe highlight-current-row>
          <el-table-column type="index" align="center" label="序号"/>
          <el-table-column prop="brand" label="品牌" align="center"/>
          <el-table-column prop="model" label="型号" align="center"/>
          <el-table-column prop="year" label="生产年份" align="center"/>
          <el-table-column prop="price" label="价格 (元)" align="center"/>
          <el-table-column prop="createdAt" label="创建时间" align="center"/>
          <el-table-column prop="updatedAt" label="更新时间" align="center"/>
          <el-table-column label="操作" align="center">
            <template #default="scope">
              <el-button type="primary" size="mini" @click="handleEdit(scope.row)">编辑</el-button>
              <el-button size="mini" type="danger" @click="handleDelete(scope.row.vehicleID)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="pagination-container">
          <el-pagination class="pagination" @current-change="findPage" :current-page="pagination.currentPage"
                         :page-size="pagination.pageSize" layout="total, prev, pager, next, jumper"
                         :total="pagination.total"/>
        </div>

        <!-- 新增/编辑汽车信息弹窗 -->
        <el-dialog title="汽车信息操作" v-model="dialogFormVisible">
          <el-form :model="formData" :rules="formRules" label-position="right" label-width="100px" ref="formRef">
            <el-form-item label="品牌" prop="brand">
              <el-input v-model="formData.brand" placeholder="请输入汽车品牌"/>
            </el-form-item>
            <el-form-item label="型号" prop="model">
              <el-input v-model="formData.model" placeholder="请输入汽车型号"/>
            </el-form-item>
            <el-form-item label="生产年份" prop="year">
              <el-input v-model.number="formData.year" placeholder="请输入生产年份"/>
            </el-form-item>
            <el-form-item label="价格 (元)" prop="price">
              <el-input v-model.number="formData.price" placeholder="请输入价格"/>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取消</el-button>
            <el-button type="primary" @click="handleSave">确定</el-button>
          </div>
        </el-dialog>
      </div>
    </div>
  </div>
</template>

<script>
import {reactive, onMounted, toRefs} from "vue";
import service from "@/util/http"; // 假设已有封装的 HTTP 请求库
import {ElMessage, ElMessageBox} from "element-plus";

export default {
  setup() {
    const data = reactive({
      formRef: {},
      pagination: {
        currentPage: 1,
        pageSize: 5,
        total: 0,
        queryString: "",
      },
      dataList: [], // 汽车数据
      formData: {
        vehicleID: null,
        brand: "",
        model: "",
        year: null,
        price: null,
      }, // 表单数据
      dialogFormVisible: false, // 控制新增窗口显示
      formRules: {
        brand: [{required: true, message: "品牌不能为空", trigger: "blur"}],
        model: [{required: true, message: "型号不能为空", trigger: "blur"}],
        year: [{required: true, message: "生产年份不能为空", trigger: "blur"}],
        price: [{required: true, message: "价格不能为空", trigger: "blur"}],
      },
    });

    const findPage = (page = 1) => {
      data.pagination.currentPage = page;
      const params = {
        currentPage: data.pagination.currentPage,
        pageSize: data.pagination.pageSize,
        queryString: data.pagination.queryString,
      };
      service.get("/admin/vehicles/findPage", {params}).then((response) => {
        const {records, total} = response.data.data;
        data.dataList = records;
        data.pagination.total = total;
      });
    };

    const handleCreate = () => {
      data.formData = {
        vehicleID: null,
        brand: "",
        model: "",
        year: null,
        price: null,
      };
      data.dialogFormVisible = true;
    };

    const handleSave = () => {
      const apiEndpoint = data.formData.vehicleID
          ? `/admin/vehicles/edit/${data.formData.vehicleID}`
          : "/admin/vehicles/add";
      const method = data.formData.vehicleID ? "put" : "post";

      data.formRef.validate((valid) => {
        if (valid) {
          service[method](apiEndpoint, data.formData).then((response) => {
            ElMessage.success(response.data.message);
            data.dialogFormVisible = false;
            findPage();
          });
        } else {
          ElMessage.error("操作失败，请检查输入项！");
        }
      });
    };

    const handleEdit = (row) => {
      data.formData = {...row}; // 初始化数据
      data.dialogFormVisible = true; // 打开弹窗
    };

    const handleDelete = (id) => {
      ElMessageBox.confirm("确定要删除这条信息吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
          .then(() => {
            service.post(`/admin/vehicles/delete/${id}`).then((response) => {
              ElMessage.success(response.data.message);
              findPage();
            });
          })
          .catch(() => {
            ElMessage.info("已取消操作");
          });
    };

    onMounted(() => {
      findPage();
    });

    return {...toRefs(data), findPage, handleCreate, handleSave, handleEdit, handleDelete};
  },
};
</script>

<style scoped>
.pagination-container {
  margin-top: 20px;
  text-align: right;
}
</style>
